package org.linlinjava.litemall.wx.manage;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import org.linlinjava.litemall.core.notify.AwsNotifyService;
import org.linlinjava.litemall.core.notify.NoticeHelper;
import org.linlinjava.litemall.core.util.GeneratorUtil;
import org.linlinjava.litemall.core.util.RegexUtil;
import org.linlinjava.litemall.db.beans.Constants;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.wx.constant.LitemallWXConstants;
import org.linlinjava.litemall.wx.dto.BuyGiveeMemberDTO;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

import static org.linlinjava.litemall.wx.util.WxResponseCode.MOBILE_CODE_ONE;

/**
 * wx支付会员用户管理服务
 *
 * @author yliyun
 * @date 2022/10/20
 */
@Service
@RequiredArgsConstructor
public class WxPayMemberUserManageService {

    /**
     * 注意助手
     */
    private final NoticeHelper noticeHelper;

    /**
     * aws通知服务
     */
    private final AwsNotifyService awsNotifyService;

    /**
     * 卢米埃成员福利优惠服务
     */
    private final LumiereMemberWelfareCouponService lumiereMemberWelfareCouponService;

    /**
     * litemall优惠券服务
     */
    private final LitemallCouponService litemallCouponService;

    /**
     * litemall优惠券用户服务
     */
    private final LitemallCouponUserService litemallCouponUserService;

    /**
     * 卢米埃成员福利订阅服务
     */
    private final LumiereMemberWelfareSubscribeService lumiereMemberWelfareSubscribeService;

    /**
     * 卢米埃订阅用户服务
     */
    private final LumiereSubscribeUserService lumiereSubscribeUserService;

    /**
     * litemall礼品卡服务
     */
    private final LitemallGiftCardService litemallGiftCardService;

    /**
     * litemall礼品卡用户服务
     */
    private final LitemallGiftCardUserService litemallGiftCardUserService;

    /**
     * litemall用户服务
     */
    private final LitemallUserService litemallUserService;

    /**
     * 卢米埃订阅规则服务
     */
    private final LumiereSubscribeRuleService lumiereSubscribeRuleService;

    /**
     * 给存在用户发送通知
     *
     * @param giveeUser              givee用户
     * @param buyGiveeMemberDto 钱买givee成员dto
     * @param payMember              付费会员
     * @param user                   用户
     * @param memberUser             会员用户
     * @param endT                   endt
     */
    public void sendNotificationToExistUser(LitemallUser giveeUser, BuyGiveeMemberDTO buyGiveeMemberDto, LumierePayMember payMember, LitemallUser user, LumierePayMemberUser memberUser, LocalDateTime endT){
        buyGiveeMemberDto.setMessage(StrUtil.isNotEmpty(buyGiveeMemberDto.getMessage())? buyGiveeMemberDto.getMessage(): LitemallWXConstants.WX_GIFTCARD_DEFAULT_MESSAGE);
        /**TODO 给被赠送者发通知 （有账号的用户）*/
        if(StrUtil.isNotEmpty(giveeUser.getMobile())) {
            awsNotifyService.sendSms(MOBILE_CODE_ONE + giveeUser.getMobile(),
                    String.format(LitemallWXConstants.WX_PAYMEMBER_GIVEEUSER_SENDSMS,user.getNickname(),user.getUsername(),LitemallWXConstants.WX_PAYMEMBER_GETTHELINK,user.getUsername(),buyGiveeMemberDto.getMessage())
                    , Constants.AWS_MESSAGE_TYPE_PROMOTIONAL);
        }else if(StrUtil.isNotEmpty(giveeUser.getEmail())){
            awsNotifyService.noticeMail(String.format(LitemallWXConstants.WX_PAYMEMBER_GIVEEUSER_TITLE_NOTICEMAIL,giveeUser.getUsername(),giveeUser.getId()),
                    String.format(LitemallWXConstants.WX_PAYMEMBER_GIVEEUSER_NOTICEMAIL,user.getNickname(),user.getUsername(),LitemallWXConstants.WX_PAYMEMBER_GETTHELINK,user.getUsername(),buyGiveeMemberDto.getMessage()),
                    String.format(LitemallWXConstants.WX_PAYMEMBER_GIVEEUSER_NOTICEMAIL,user.getNickname(),user.getUsername(),LitemallWXConstants.WX_PAYMEMBER_GETTHELINK,user.getUsername(),buyGiveeMemberDto.getMessage()),giveeUser.getEmail());
        }
        welfareGift(buyGiveeMemberDto.getMemberId(), giveeUser, buyGiveeMemberDto.getGiveeUser(), user.getId(), payMember, endT);
        //系统通知
          noticeHelper.noticeUser(Constants.MSG_TYPE_OTHER, LitemallWXConstants.WX_PAYMEMBER_GIVEEUSER_TITLE_NOTICEHELPER,
                String.format(LitemallWXConstants.WX_PAYMEMBER_GIVEEUSER_NOTICEHELPER,user.getNickname(),user.getUsername(),user.getUsername(),buyGiveeMemberDto.getMessage())
                , giveeUser.getId(), memberUser);

        /**TODO 给自己发系统通知*/
          noticeHelper.noticeUser(Constants.MSG_TYPE_OTHER, LitemallWXConstants.WX_PAYMEMBER_USER_TITLE_NOTICEHELPER,
                String.format(LitemallWXConstants.WX_PAYMEMBER_USER_NOTICEHELPER,giveeUser.getUsername())
                , user.getId(), memberUser);
          awsNotifyService.sendSms(MOBILE_CODE_ONE + user.getMobile(),
                String.format(LitemallWXConstants.WX_PAYMEMBER_USER_NOTICEHELPER,buyGiveeMemberDto.getGiveeUser())
                ,Constants.AWS_MESSAGE_TYPE_PROMOTIONAL);
    }

    /**
     * 给不存在用户发送通知
     *
     * @param payMember              付费会员
     * @param user                   用户
     * @param buyGiveeMemberDto 钱买givee成员dto
     * @param endT                   endt
     * @param memberUser             会员用户
     */
    public void sendNotificationToNotExistUser(LumierePayMember payMember, LitemallUser user, BuyGiveeMemberDTO buyGiveeMemberDto, LocalDateTime endT, LumierePayMemberUser memberUser){
        buyGiveeMemberDto.setMessage(StrUtil.isNotEmpty(buyGiveeMemberDto.getMessage())? buyGiveeMemberDto.getMessage():LitemallWXConstants.WX_GIFTCARD_DEFAULT_MESSAGE);
        /**TODO 给被赠送者发通知 （没有账号的用户）*/
        if(RegexUtil.isMobileValid(buyGiveeMemberDto.getGiveeUser())) {
            awsNotifyService.sendSms(MOBILE_CODE_ONE + buyGiveeMemberDto.getGiveeUser(),
                    String.format(LitemallWXConstants.WX_PAYMEMBER_GIVEEUSER_SENDSMS,user.getNickname(),user.getUsername(),LitemallWXConstants.WX_PAYMEMBER_DOWNLOADLINK,user.getUsername(),buyGiveeMemberDto.getMessage())
                    ,Constants.AWS_MESSAGE_TYPE_PROMOTIONAL);
        }
        if(RegexUtil.isEmailExact(buyGiveeMemberDto.getGiveeUser())){
            awsNotifyService.noticeMail(String.format(LitemallWXConstants.WX_PAYMEMBER_GIVEEUSER_TITLE_NOTICEMAIL,user.getNickname(),user.getUsername()),
                    String.format(LitemallWXConstants.WX_PAYMEMBER_GIVEEUSER_NOTICEMAIL,user.getNickname(),user.getUsername(),LitemallWXConstants.WX_PAYMEMBER_GETTHELINK,user.getUsername(),buyGiveeMemberDto.getMessage()),
                    String.format(LitemallWXConstants.WX_PAYMEMBER_GIVEEUSER_NOTICEMAIL,user.getNickname(),user.getUsername(),LitemallWXConstants.WX_PAYMEMBER_GETTHELINK,user.getUsername(),buyGiveeMemberDto.getMessage()),buyGiveeMemberDto.getGiveeUser() );
        }
        welfareGift(buyGiveeMemberDto.getMemberId(), null, buyGiveeMemberDto.getGiveeUser(), user.getId(), payMember, endT);
        /**TODO 给自己发系统通知*/
        noticeHelper.noticeUser(Constants.MSG_TYPE_OTHER, LitemallWXConstants.WX_PAYMEMBER_USER_TITLE_NOTICEHELPER,
                String.format(LitemallWXConstants.WX_PAYMEMBER_USER_NOTICEHELPER,buyGiveeMemberDto.getGiveeUser())
                , user.getId(), memberUser);
        awsNotifyService.sendSms(MOBILE_CODE_ONE + user.getMobile(),
                String.format(LitemallWXConstants.WX_PAYMEMBER_USER_NOTICEHELPER,buyGiveeMemberDto.getGiveeUser())
                ,Constants.AWS_MESSAGE_TYPE_PROMOTIONAL);
    }

    /**
     * 福利礼品
     * 赠送礼物卡，优惠券，订阅
     *
     * @param memberId  成员身份
     * @param giveeUser givee用户
     * @param userName  用户名
     * @param userId    用户id
     * @param payMember 付费会员
     * @param endT      endt
     */
    public void welfareGift(Integer memberId, LitemallUser giveeUser,
                            String userName, Integer userId, LumierePayMember payMember, LocalDateTime endT) {
        //添加优惠券
        List<LumiereMemberWelfareCoupon> welfareCoupons = lumiereMemberWelfareCouponService.findByMemberId(memberId, (byte) 2);

        welfareCoupons.stream().forEach(welfareCoupon -> {
            Integer couponNum = welfareCoupon.getNumbers();
            LitemallCoupon coupon = litemallCouponService.findById(welfareCoupon.getCouponId());

            if (coupon != null) {
                LocalDateTime startT = coupon.getStartTime();
                LocalDateTime endTime = coupon.getEndTime();
                if(coupon.getTimeType().equals((short)0)){
                    startT = LocalDateTime.now();
                    endTime = startT.plusDays(coupon.getDays());
                }

                for (Integer i = 0; i < couponNum; i++) {
                    LitemallCouponUser litemallCouponUser = new LitemallCouponUser();
                    litemallCouponUser.setStartTime(startT);
                    litemallCouponUser.setEndTime(endTime);
                    litemallCouponUser.setStatus((short) 0);
                    litemallCouponUser.setCouponId(coupon.getId());
                    litemallCouponUser.setAddTime(LocalDateTime.now());
                    litemallCouponUser.setUpdateTime(LocalDateTime.now());
                    litemallCouponUser.setDeleted(false);
                    litemallCouponUser.setUserId(giveeUser != null ? giveeUser.getId() : null);
                    litemallCouponUser.setUserName(userName);
                    litemallCouponUserService.add(litemallCouponUser);
                }
            }
        });

        //添加用户订阅
        List<LumiereMemberWelfareSubscribe> welfareSubscribes = lumiereMemberWelfareSubscribeService.findByMemberId(memberId, (byte) 2);

        welfareSubscribes.stream().forEach(welfareSubscribe -> {
            Integer[] selectRuleIds = welfareSubscribe.getSubscribeRuleIds();
            LumiereSubscribeUser subscribeUser = addSubscribeUser(userId, welfareSubscribe.getSubscribeId(), selectRuleIds, endT, userName, giveeUser);
            lumiereSubscribeUserService.add(subscribeUser);
        });


        //添加礼物卡
        if (payMember.getGiftCardIds() != null) {
            Integer[] giftCardIds = payMember.getGiftCardIds();
            for (int i = 0; i < giftCardIds.length; i++) {
                LitemallGiftCard litemallGiftCard = litemallGiftCardService.findById(giftCardIds[i]);
                if (litemallGiftCard != null) {
                    LitemallGiftCardUser giftCardUser = new LitemallGiftCardUser();
                    giftCardUser.setIsDefault(0);

                    String cardNumber = GeneratorUtil.cardNumberGenerator("00", userId);
                    LitemallGiftCardUser cardUser = litemallGiftCardUserService.findByNumber(cardNumber);
                    while (cardUser != null) {
                        cardNumber = GeneratorUtil.cardNumberGenerator("00", userId);
                        cardUser = litemallGiftCardUserService.findByNumber(cardNumber);
                    }
                    giftCardUser.setCardNumber(cardNumber);
                    giftCardUser.setUserId(giveeUser != null ? giveeUser.getId() : null);
                    giftCardUser.setAmount(BigDecimal.ZERO);
                    giftCardUser.setStatus(0);
                    giftCardUser.setDeleted(false);
                    giftCardUser.setAddTime(LocalDateTime.now());
                    giftCardUser.setUpdateTime(LocalDateTime.now());
                    giftCardUser.setGiftCardId(giftCardIds[i]);
                    litemallGiftCardUserService.add(giftCardUser);
                }
            }
        }

    }


    /**
     * 添加订阅用户
     *
     * @param userId        用户id
     * @param subscribeId   订阅id
     * @param selectRuleIds 选择规则id
     * @param endT          endt
     * @param givee         givee
     * @param giveeUser     givee用户
     * @return {@link LumiereSubscribeUser}
     */
    public LumiereSubscribeUser addSubscribeUser(Integer userId, Integer subscribeId, Integer[] selectRuleIds,
                                                 LocalDateTime endT, String givee, LitemallUser giveeUser) {

        LitemallUser user = litemallUserService.findById(userId);

        LumiereSubscribeUser lumiereSubscribeUser = new LumiereSubscribeUser();
        lumiereSubscribeUser.setPurchaserId(userId);
        if (lumiereSubscribeUser.getUserId() == null) {
            lumiereSubscribeUser.setUserId(giveeUser != null ? giveeUser.getId() : userId);
        }

        LumiereSubscribeRule rule = lumiereSubscribeRuleService.findById(selectRuleIds[0]);

        lumiereSubscribeUser.setSubscribeId(subscribeId);

        lumiereSubscribeUser.setStatus(Constants.SUBSCRIBE_USER_MEMBER_NOT_CONFIRM);

        lumiereSubscribeUser.setAutoSub(false);

        lumiereSubscribeUser.setPurchaserId(giveeUser != null ? giveeUser.getId() : null);

        lumiereSubscribeUser.setUserName(giveeUser != null ? giveeUser.getUsername() : user != null ? user.getUsername() : null);

        lumiereSubscribeUser.setPrice(BigDecimal.ZERO);

        lumiereSubscribeUser.setStartTime(LocalDateTime.now());

        if(rule != null) {
            if (rule.getRuleType().equals((byte) 1)) {
                lumiereSubscribeUser.setEndTime(LocalDateTime.now().plusWeeks(1));
            } else if (rule.getRuleType().equals((byte) 2)) {
                lumiereSubscribeUser.setEndTime(LocalDateTime.now().plusMonths(1));
            } else {
                lumiereSubscribeUser.setEndTime(LocalDateTime.now().plusYears(1));
            }
        }
        lumiereSubscribeUser.setRuleId(selectRuleIds[0]);

        return lumiereSubscribeUser;
    }







}
